package cn.jiangzeyin.aes;

import cn.jiangzeyin.RandomUtil;

/**
 * 代理使用类
 * Created by jiangzeyin on 2018/3/15.
 */
public class AES_Proxy {
    private static final Integer[] INTEGERS = {4, 6, 8};

    private static final int START_I = 4;
    private static final int START_I2 = START_I + 1;

    /**
     * 生成随机字符串
     *
     * @return 数组
     */
    private static String[] getRandomString() {
        int length = RandomUtil.getRandomArray(INTEGERS);
        return new String[]{length + "", RandomUtil.getRandomString(length)};
    }

    /**
     * 解密
     *
     * @param data 密文
     * @return 解密后
     */
    public static String decode(String data) {
        String index = data.substring(4, 5);
        int len = Integer.parseInt(index);
        String key = data.substring(5, 5 + len);
        data = data.substring(0, 4) + data.substring(4 + 1 + len);
        return new AES().decrypt(key, data);
    }

    /**
     * 加密
     *
     * @param data 要加密的字符串
     * @return 加密后的
     */
    public static String encode(String data) {
        String[] keys = getRandomString();
        String s = new AES().encrypt(keys[1], data.getBytes());
        StringBuilder stringBuffer = new StringBuilder(s);
        stringBuffer.insert(4, keys[0] + keys[1]);
        return stringBuffer.toString();
    }
}
